import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import supabase from '../../lib/supabase';

// 模拟模式配置
const USE_MOCK_DATA = !process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL === 'https://your-project.supabase.co';

// 模拟数据库存储预约信息
interface MockAppointmentData {
  id: string;
  name: string;
  phone: string;
  other_contact?: string;
  remark?: string;
  date: string;
  time_slot: string;
  created_at: string;
}

// 模拟数据库
let mockAppointments: MockAppointmentData[] = [];

// 初始化模拟数据
function initializeMockData() {
  if (mockAppointments.length === 0) {
    // 获取今天和明天的日期
    const today = new Date().toISOString().split('T')[0];
    const tomorrow = new Date(Date.now() + 86400000).toISOString().split('T')[0];
    
    // 添加一些模拟预约数据
    mockAppointments = [
      {
        id: '1',
        name: '张三',
        phone: '13800138001',
        date: today,
        time_slot: '09:30-10:00',
        created_at: new Date().toISOString(),
      },
      {
        id: '2',
        name: '李四',
        phone: '13900139001',
        date: today,
        time_slot: '15:00-15:30',
        created_at: new Date(Date.now() - 3600000).toISOString(),
      },
      {
        id: '3',
        name: '王五',
        phone: '13700137001',
        date: tomorrow,
        time_slot: '10:30-11:00',
        created_at: new Date(Date.now() - 7200000).toISOString(),
      },
      {
        id: '4',
        name: '赵六',
        phone: '13600136001',
        date: tomorrow,
        time_slot: '14:30-15:00',
        created_at: new Date(Date.now() - 10800000).toISOString(),
      }
    ];
  }
}

// GET请求：获取预约信息（根据日期筛选或获取所有）
export async function GET(request: NextRequest) {
  const date = request.nextUrl.searchParams.get('date');
  const getAll = request.nextUrl.searchParams.get('all') === 'true';
  
  try {
    // 在模拟模式下使用模拟数据
    if (USE_MOCK_DATA) {
      initializeMockData();
      
      // 如果指定了date参数，则查询该日期的预约时间段
      if (date && !getAll) {
        const reservedSlots = mockAppointments
          .filter(appointment => appointment.date === date)
          .map(appointment => appointment.time_slot);
        
        return NextResponse.json({
          date,
          reservedSlots,
          total: reservedSlots.length
        });
      }
      // 如果指定了all=true，则获取所有预约信息
      else if (getAll) {
        return NextResponse.json({
          total: mockAppointments.length,
          appointments: mockAppointments
        });
      }
      
      // 如果既没有指定date，也没有指定all=true，则返回错误
      return NextResponse.json(
        { error: '请提供日期参数或设置all=true来获取所有预约' },
        { status: 400 }
      );
    }
    
    // 非模拟模式下，使用Supabase数据库
    // 如果指定了date参数，则查询该日期的预约时间段
    if (date && !getAll) {
      const { data, error } = await supabase
        .from('appointments')
        .select('time_slot')
        .eq('date', date);
      
      if (error) {
        console.error('查询已预约时间段失败:', error);
        return NextResponse.json(
          { error: '查询失败，请稍后重试' },
          { status: 500 }
        );
      }
      
      // 提取时间段数据
      const reservedSlots = data.map(appointment => appointment.time_slot);
      
      return NextResponse.json({
        date,
        reservedSlots,
        total: reservedSlots.length
      });
    } 
    // 如果指定了all=true，则获取所有预约信息
    else if (getAll) {
      const { data, error, count } = await supabase
        .from('appointments')
        .select('*', { count: 'exact' })
        .order('created_at', { ascending: false });
      
      if (error) {
        console.error('获取所有预约失败:', error);
        return NextResponse.json(
          { error: '获取失败，请稍后重试' },
          { status: 500 }
        );
      }
      
      return NextResponse.json({
        total: count || 0,
        appointments: data || []
      });
    }
    
    // 如果既没有指定date，也没有指定all=true，则返回错误
    return NextResponse.json(
      { error: '请提供日期参数或设置all=true来获取所有预约' },
      { status: 400 }
    );
  } catch (error) {
    console.error('服务器错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后重试' },
      { status: 500 }
    );
  }
}

// POST请求：创建新的预约
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, phone, otherContact, remark, date, timeSlot } = body;
    
    // 验证必填字段
    if (!name || !phone || !date || !timeSlot) {
      return NextResponse.json(
        { error: '姓名、手机号码、预约日期和时间段为必填项' },
        { status: 400 }
      );
    }
    
    // 验证手机号码格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return NextResponse.json(
        { error: '请输入正确的手机号码' },
        { status: 400 }
      );
    }
    
    // 在模拟模式下使用模拟数据
    if (USE_MOCK_DATA) {
      initializeMockData();
      
      // 检查时间段是否已被预约
      const isSlotReserved = mockAppointments.some(
        appointment => appointment.date === date && appointment.time_slot === timeSlot
      );
      
      if (isSlotReserved) {
        return NextResponse.json(
          { error: '该时间段已被预约，请选择其他时间' },
          { status: 409 }
        );
      }
      
      // 创建新的预约
      const newAppointment: MockAppointmentData = {
        id: Date.now().toString(),
        name,
        phone,
        other_contact: otherContact,
        remark,
        date,
        time_slot: timeSlot,
        created_at: new Date().toISOString()
      };
      
      // 添加到模拟数据库
      mockAppointments.push(newAppointment);
      
      // 返回成功响应
      return NextResponse.json(
        { success: true, appointment: newAppointment },
        { status: 201 }
      );
    }
    
    // 非模拟模式下，使用Supabase数据库
    // 检查时间段是否已被预约
    const { data: existingAppointments, error: checkError } = await supabase
      .from('appointments')
      .select('id')
      .eq('date', date)
      .eq('time_slot', timeSlot)
      .limit(1);
    
    if (checkError) {
      console.error('检查预约冲突失败:', checkError);
      return NextResponse.json(
        { error: '检查失败，请稍后重试' },
        { status: 500 }
      );
    }
    
    if (existingAppointments.length > 0) {
      return NextResponse.json(
        { error: '该时间段已被预约，请选择其他时间' },
        { status: 409 }
      );
    }
    
    // 创建新的预约
    const { data: newAppointment, error: insertError } = await supabase
      .from('appointments')
      .insert({
        name,
        phone,
        other_contact: otherContact,
        remark,
        date,
        time_slot: timeSlot,
        created_at: new Date().toISOString()
      })
      .select();
    
    if (insertError) {
      console.error('创建预约失败:', insertError);
      return NextResponse.json(
        { error: '创建预约失败，请稍后重试' },
        { status: 500 }
      );
    }
    
    // 返回成功响应
    return NextResponse.json(
      { success: true, appointment: newAppointment[0] },
      { status: 201 }
    );
  } catch (error) {
    console.error('创建预约时发生错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后重试' },
      { status: 500 }
    );
  }
}